package tools.clustering.DistanceGenerators;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;
import java.util.ArrayList;
import java.util.HashMap;

public class WordDistanceMatrix {

	private static double distance=1;
	
	public static void createMatrix(String infile, String outprefix)throws Exception{
		BufferedReader in =new BufferedReader(new FileReader(infile));
		in.readLine();
		HashMap<String, ArrayList<String>> datum=new HashMap<String, ArrayList<String>>();
		ArrayList<String> ids=new ArrayList<String>(),l1,l2;
		String[] l;
		int j=0;
		double dist,minLength,maxLength;
		String s1,s2;
		BufferedWriter out=new BufferedWriter(new FileWriter(outprefix+"_names.csv"));
		for(String s=in.readLine();s!=null;s=in.readLine()){
			l=s.split("\t");
			ArrayList<String>tmp=new ArrayList<String>();
			ids.add(l[0]);
			out.write(j+++"\t"+l[0]+"\n");
			for(int i=1;i<l.length;i++){
				tmp.add(l[i]);
			}
			datum.put(l[0], tmp);
		}
		out.close();
		out=new BufferedWriter(new FileWriter(outprefix+"_matrix.csv"));
		for(Object o1: ids.toArray()){
			for(Object o2:ids.toArray()){
				//calculate distance
				if(o1.equals(o2)){
					out.write("0\t");
				}else{
					l1=datum.get(o1);
					l2=datum.get(o2);
					dist=0;
					if(l1.size()<l2.size()){
						minLength=l1.size();
						maxLength=l2.size();
					}else{
						minLength=l2.size();
						maxLength=l1.size();
					}
					for(int i=0;i<minLength;i++){
						s1=l1.get(i);
						s2=l2.get(i);
						if(s1.equals(s2)){
							dist+=0*distance;
						}else if(s1.length()==0||s2.length()==0){
							dist+=1*distance;
						}else{
							dist+=2*distance;
						}
					}
					dist+=(maxLength-minLength)*distance;
					out.write(dist+"\t");
				}
			}
			out.write("\n");
		}
		out.close();
	}
}
